<template>
  <div>
    <el-popover v-if="columns.filter((i) => i.show).length" popper-class="express-entrance" trigger="click" v-model="showPopover">
    <button
      class="base-btn base-btn--round express-entrance__button"
      type="button"
      slot="reference"
    >
      <i class="iconfont icon-add1"></i>
    </button>
    <div class="express-entrance__content">
      <div
        class="express-entrance__item"
        v-for="item in columns.filter((i) => i.show)"
        :key="item.fieldName"
        @click="openQuickTab(item)"
      >
        <i :class="['iconfont', item.icon, 'type-icon']" />
        <span :class="['content']">
          {{ item.displayName }}
        </span>
      </div>
    </div>
    
    <div class="express-entrance_setting"  @click="openSetting">
      <i class="iconfont icon-setting"></i>
      <span class="content">{{ $t('common.base.set') }}</span>
    </div>
  </el-popover>
    <el-popover v-else ref="popover_noData" trigger="click" v-model="showNoData">
      <button
        class="base-btn base-btn--round express-entrance__button"
        type="button"
        slot="reference"
      >
        <i class="iconfont icon-add1"></i>
      </button>
      <div class="express-entrance_noData">
        <div :style="{ backgroundImage: 'url(' + noDataImage + ')' }" class="content"></div>
        <el-button type="text" @click="openSetting">{{ $t('im.imChat.goSet') }}</el-button>
      </div>
    </el-popover>
    <select-column ref="advanced" @save="saveColumnStatus" :modalTitle="$t('setting.enterprise.quickEntrance.title')"/>
  </div>
</template>

<script>
import { getQuickEntrance } from '@src/api/WorkbenchApi';
import { getAllTemplateList } from '@src/api/PassApi';
import { projectTypeList } from '@src/api/ProjectManage';
import { creatServerCachApi, getUserGuideStorageFor } from '@src/api/GuideApi';
import { ref, defineComponent, unref, computed, getCurrentInstance, onMounted, watch } from 'vue';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum'
import AuthUtil from '@src/util/auth';
import { platform } from '@src/platform';
import { useOpenTab } from '@src/modules/projectManage/projectManageList/hooks/useOpenTab';
import { message } from '@src/util/message'
import i18n from '@src/locales'
/* mixin */
import {
  VersionControlTaskMixin,
  VersionControlCalendarMixin,
  VersionControlWikiMixin
} from '@src/mixins/versionControlMixin'
import { getOssUrl } from '@src/util/assets'
import draggable from 'vuedraggable';
import SelectColumn from './component/selectColumn';
const noDataImage = getOssUrl('/no_data.png');

const quickEntranceMap = {
  eventCreate: {
    entrance: 'event',
    type: PageRoutesTypeEnum.PageCreateEvent,
    icon: 'icon-caidan_fuwutai',
    id: 'event',
    name: i18n.t('common.pageTitle.pageCreateEvent'),
    // url: '/event/edit',
		trackId: 'CREATE_EVENT'
  },
  taskCreate: {
    entrance: 'task',
    type: PageRoutesTypeEnum.PageCreateTask,
    icon: 'icon-caidan_gongdanmokuai',
    id: 'task',
    name: i18n.t('common.pageTitle.pageCreateTask'),
    // url: '/task/edit',
		trackId: 'CREATE_TASK'
  },
  customerCreate: {
    entrance: 'customer',
    type: PageRoutesTypeEnum.PageCreateCustomer,
    icon: 'icon-caidan_kehumokuai',
    id: 'customer',
    name: i18n.t('common.pageTitle.pageCreateCustomer'),
    // url: '/customer/create',
		trackId: 'CREATE_CUSTOMER'
  },
  productCreate: {
    entrance: 'product',
    type: PageRoutesTypeEnum.PageCreateProduct,
    icon: 'icon-caidan-chanpin',
    id: 'product',
    name: i18n.t('common.pageTitle.pageCreateProduct'),
    // url: '/customer/product/create',
		trackId: 'CREATE_PRODUCT'
  },
  documentCreate: {
    entrance: 'wiki',
    type: PageRoutesTypeEnum.PageWikiCreate,
    icon: 'icon-read-fill',
    id: 'wiki',
    name: i18n.t('frameHeader.ExpressEntrance.createKnowledgeBase'),
    // url: '/wiki/create/page',
		trackId: 'CREATE_WIKI'
  },
  informationCreate: {
    entrance: 'informationAnnouncement',
    type: PageRoutesTypeEnum.PageBulletinCreate,
    icon: 'icon-caidan_xinxiguanli',
    id: 'informationAnnouncement',
    name: i18n.t('frameHeader.ExpressEntrance.createMessage'),
    // url: '/info/notice/create/page',
		trackId: 'CREATE_ANNOUNCEMENT'
  },
  scheduleCreate: {
    entrance: 'schedule',
    type: PageRoutesTypeEnum.PageSchedule,
    icon: 'icon-caidan-richengguanli',
    id: 'schedule',
    name: i18n.t('frameHeader.ExpressEntrance.createSchedule'),
    // url: '/calendar?type=create',
		trackId: 'CREATE_SCHEDULE',
    params: 'type=create'
  },
  itemsNewCreate: {
    entrance: 'itemsNew',
    type: PageRoutesTypeEnum.PageItemsNew,
    icon: 'icon-caidan_beijianguanli',
    id: 'itemsNew',
    name: i18n.t('frameHeader.ExpressEntrance.pageItemsNew'),
    // url: '/itemsNew?type=create',
    trackId: 'CREATE_ITEMS_NEW',
    params: 'type=create'
  },
};

export default defineComponent({
  name: 'express-entrance',
  props: {
    initData: {
      type: Object,
       default: {},
    },
  },
  mixins: [
    VersionControlTaskMixin,
    VersionControlCalendarMixin,
    VersionControlWikiMixin
  ],
  computed: {
    rightData() {
      return this.data.filter((item) => this.value.includes(item.key));
    },
  },
  components: {
    draggable,
    SelectColumn,
  },
  setup(props) {

    const instance = getCurrentInstance()
    const _isShowTaskModule = computed(() => Boolean(instance?.proxy?._isShowTaskModule))
    const _isShowCalendarModule = computed(() => Boolean(instance?.proxy?._isShowCalendarModule))
    const _isShowWikiModule = computed(() => Boolean(instance?.proxy?._isShowWikiModule))

    const auth = props.initData.user?.auth || {}
    const allowCreateTask = AuthUtil.hasAuth(auth, 'TASK_ADD')
    const allowCreateCustomer = AuthUtil.hasAuth(auth, 'CUSTOMER_CREATE')
    const allowCreateEvent = AuthUtil.hasAuth(auth, 'CASE_ADD')
    const allowCreateWiki = AuthUtil.hasAuth(auth, 'VIP_INFO_CREATE')
    const allowCreateSchedule = AuthUtil.hasAuth(auth, 'CALENDAR_ADD')
    const allowCreateProduct = AuthUtil.hasAuth(auth, 'PRODUCT_CREATE')
    const allowCreateBulletin = AuthUtil.hasAuth(auth, 'VIP_INFO_NOTICE_CREATE')
    const allowCreateProject = AuthUtil.hasAuth(auth, 'PROJECT_CREATE') // 新建项目
    const allowCreateMaterial = AuthUtil.hasAuth(auth, 'MATERIAL_ADD') // 新建物料


    const quickEntranceList = computed(() => {
      // 枚举值由后端改为放在前端
      return [
        {
          name: i18n.t('common.pageTitle.pageCreateTask'),
          type: 'taskCreate',
          selected: true,
          show: allowCreateTask && _isShowTaskModule.value,
          icon: 'icon-caidan_gongdanmokuai'
        },
        {
          name: i18n.t('common.pageTitle.pageCreateCustomer'),
          type: 'customerCreate',
          selected: true,
          show: allowCreateCustomer,
          icon: 'icon-caidan_kehumokuai'
        },
        {
          name: i18n.t('common.pageTitle.pageCreateEvent'),
          type: 'eventCreate',
          selected: true,
          show: allowCreateEvent,
          icon: 'icon-caidan_fuwutai'
          },
        {
          name: i18n.t('common.pageTitle.pageNewKnowledge'),
          type: 'documentCreate',
          selected: true,
          show: allowCreateWiki && _isShowWikiModule.value,
          icon: 'icon-read-fill'
        },
        {
          name: i18n.t('common.pageTitle.pageNewSchedule'),
          type: 'scheduleCreate',
          selected: true,
          show: allowCreateSchedule && _isShowCalendarModule.value,
          icon: 'icon-caidan-richengguanli'
        },
        {
          name: i18n.t('common.pageTitle.pageCreateProduct'),
          type: 'productCreate',
          selected: true,
          show: allowCreateProduct,
          icon: 'icon-caidan-chanpin'
        },
        {
          name: i18n.t('common.pageTitle.pageNewBulletin'),
          type: 'informationCreate',
          selected: true,
          show: allowCreateBulletin,
          icon: 'icon-caidan_xinxiguanli'
        },
        {
          name: i18n.t('common.pageTitle.pageItemsNew'),
          type: 'itemsNewCreate',
          selected: true,
          show: allowCreateMaterial,
          icon: 'icon-caidan_beijianguanli'
        }
      ]
    })

    // 打开对应快捷入口页面
    function openQuickTab(item) {
      if (item.type == 'customLink') {
        window.open(item.url);
        return;
      } else if (item.type == 'paas') {
        platform.openTab({
          url: item.url,
          title: item.displayName,
        });
        return;
      } else if (item.type == 'project') {
        const { openProjectCreateTab } = useOpenTab();
        openProjectCreateTab(item.fieldName);
        return;
      }
      let { params = '', type, url, trackId, name } = quickEntranceMap[item.type] || {};
      if (!type) return console.error(`type: ${item.type} url is not defined`);

			this.$track.clickStat(this.$track.formatParams(`NAV_${trackId}`, name))

      if (item.name === '新建日程') {
        params += `&random=${Math.random()}`;
      }
      openAccurateTab({
        type,
        reload: true,
        params
      });
    }

    const showPopover = ref(false);
    const showNoData = ref(false);
    const advanced = ref(null);
    const canSave = ref(false);
    // 打开配置页面
    function openSetting() {
      showPopover.value = false;
      showNoData.value = false;
      advanced.value.open(columns.value);
    }
    // 保存配置
    function saveColumnStatus(event) {
      creatServerCachApi({
        isComplete: 1, 
        step: 1,
        type: 'quickEntrance',
        userConfig: JSON.stringify(event.data)
      }).then(res => {
        if (res.succ) {
          canSave.value = true;
          columns.value = event.data;
          message.success(i18n.t('common.base.saveSuccess'));
        } else {
          message.error(i18n.t('common.base.saveFail'));
        }
      })
    }
    
    const newColumns = ref([]);
    const columns = computed({
      get: () => canSave.value ? newColumns.value : quickEntranceList.value.filter(item => item.show).map(item => ({
        displayName: item.name,
        fieldName: item.type,
        show: true,
        root: false,
        checked: true,
        icon: item.icon,
        type: item.type,
      })),
      set: (val) => {
        newColumns.value = val;
      }
    });

    onMounted(async () => {
      const getUserConfig = await getUserGuideStorageFor({ type: 'quickEntrance' });
      if (getUserConfig?.data) {
        const passConfig = await getAllTemplateList();
        if (passConfig.success) {
          const data = passConfig.data;
          for (let i = 0; i < data.length; i++) {
            if (data[i]?.children) {
              for (let j = 0; j < data[i].children.length; j++) {
                columns.value.push({
                  displayName: i18n.t('common.base.create') + data[i].children[j].name,
                  fieldName: data[i].children[j].code,
                  type: 'paas',
                  checked: true,
                  show: false,
                  root: false,
                  url: `/paas/#/template/edit?formId=${data[i].children[j].code}&appId=${data[i].children[j].formOutBidId}&noHistory=1`,
                  icon: 'icon-fund-fill1'
                });
              }
            }
          }
        }
        if(allowCreateProject) {
          const projectConfig = await projectTypeList();
          if (projectConfig.success) {
            const data = projectConfig.data;
            for (let i = 0; i < data.length; i++) {
              columns.value.push({
                displayName: i18n.t('common.base.create') + data[i].name,
                fieldName: data[i].id,
                type: 'project',
                checked: true,
                show: false,
                root: false,
                icon: 'icon-xiangmuguanli1'
              });
            }
          }
        }
        const data = JSON.parse(getUserConfig.data?.userConfig || '[]');
        let index = 0;
        let newColumns = [];
        for (let i = 0; i < data.length; i++) {
          let flg = columns.value.findIndex(item => item.fieldName === data[i].fieldName);
          if (data[i].type == 'paas') {
            flg = columns.value.findIndex(item => item.fieldName === data[i].fieldName);
          }
          if (flg > -1) {
            columns.value[flg].show = data[i].show;
            newColumns[index] = columns.value[flg];
            index++;
          } else if (data[i].type === 'customLink') {
            newColumns[index] = data[i];
            index++;
          }
        }
        for (let i = 0; i < columns.value.length; i++) {
          if (newColumns.findIndex(item => item.fieldName === columns.value[i].fieldName) === -1) {
            newColumns[index] = columns.value[i];
            index++;
          }
        }
        canSave.value = true;
        columns.value = newColumns;
      }
    });

    return {
      quickEntranceList,
      openQuickTab,
      noDataImage,
      openSetting,
      showPopover,
      showNoData,
      advanced,
      saveColumnStatus,
      columns,
    };
  },
});
</script>
<style lang="scss">
.express-entrance__content {
  max-height: 300px;
  overflow-y: auto;
}
.express-entrance {
  padding: 4px 0;
}
.express-entrance__item {
  padding: 4px 4px 4px 16px;
  width: 100%;
  height: 32px;
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;

  &:hover {
    background: $color-primary-light-1 !important;
    // background: #f5f5f5 !important;
    color: $color-primary !important;
  }

  .type-icon {
    font-size: 14px;
    color: $color-primary;
  }
  .content {
    padding: 0 8px;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.express-entrance__button {
  margin-right: 12px;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  background: $color-primary;

  &:hover {
    background: $color-primary-light-5;
  }
  i {
    font-size: 12px;
  }
}
.express-entrance_setting {
  width: 100%;
  height: 32px;
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
  border-top: 1px solid #e4e7ed;
  padding: 9px 16px;
  .icon-setting {
    font-size: 14px;
    color: #8c8c8c;
  }
  .content {
    padding: 0 8px;
    font-size: 14px;
    color: #8c8c8c;
  }
}

.express-entrance_noData {
  width: 136px;
  height: 148px;
  padding: 30px 0;
  text-align: center;
  .content {
    width: 60px;
    height: 60px;
    margin: 0 auto;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
  }
}
</style>